import time

import pandas as pd
import mplfinance as mpf


from tools import picture_upload
from tools.dingdingrobot import call_dingtalk


# 接收一个df

def  Boll(data_df, period=20, ndev = 2):
    history_candles = data_df.copy()
    if "ts" in data_df.columns:
        history_candles.sort_values(by="ts", ascending=True, inplace=True)
    if 'date' in data_df.columns:
        # 如果存在，将其设置为索引
        data_df.set_index('date', inplace=True)
    if 'trade_time' in data_df.columns:
        # 如果存在，将其设置为索引
        data_df.set_index('trade_time', inplace=True)
    # history_candles.reset_index(drop=True, inplace=True)
    # 假设df是已经存在的DataFrame，并且包含列名"open", "high", "low", "close"
    history_candles.rename(columns={'open': 'o', 'high': 'h', 'low': 'l', 'close': 'c'}, inplace=True)


    # 计算中轨（简单移动平均）
    history_candles['MiddleBand'] = history_candles['c'].rolling(window=period).mean()

    # 计算布林中轨的差值
    history_candles['BoolingDiff'] = history_candles['MiddleBand'] .diff()


    # 计算标准差
    history_candles['STD'] = history_candles['c'].rolling(window=period).std()

    # 计算上轨和下轨
    history_candles['UpperBand'] = history_candles['MiddleBand'] + (history_candles['STD'] * ndev)
    history_candles['LowerBand'] = history_candles['MiddleBand'] - (history_candles['STD'] * ndev)
    if "v" in history_candles.columns:
        history_candles.rename(columns={'o': 'Open', 'h': 'High', 'l': 'Low', 'c': 'Close', 'v': 'Volume'}, inplace=True)
    elif "volume" in history_candles.columns:
        history_candles.rename(columns={'o': 'Open', 'h': 'High', 'l': 'Low', 'c': 'Close', 'volume': 'Volume'},
                               inplace=True)
    else:
        history_candles.rename(columns={'o': 'Open', 'h': 'High', 'l': 'Low', 'c': 'Close', 'v': 'Volume'}, inplace=True)

    columns_to_convert = ['Open', 'High', 'Low', 'Close', 'Volume']
    history_candles[columns_to_convert] = history_candles[columns_to_convert].apply(pd.to_numeric, errors='coerce')

    history_candles.index = pd.to_datetime(history_candles.index)
    return history_candles


if __name__ == '__main__':
    data_df = pd.read_csv('../data_info/bit_coin.csv', index_col=0)
    result = Boll(data_df)



    # 绘制K线图和布林带

    # 创建Bollinger Bands的添加线
    apds = [
        mpf.make_addplot(result['MiddleBand'], color='blue'),
        mpf.make_addplot(result['UpperBand'], color='red'),
        mpf.make_addplot(result['LowerBand'], color='green'),
        mpf.make_addplot(result['BoolingDiff'], color='yellow')
    ]

    # 绘制K线图和Bollinger Bands
    timestamp = int(time.time())
    mpf.plot(result, type='candle', addplot=apds, style='default', volume=True)
    # 上传图片到云并推送到钉钉
    # pic_path = picture_upload.upload('bolltest{}.png'.format(timestamp))
    message = []
    pic_path = "https://s2.loli.net/2024/12/01/dwaiJVLhcTDnvo9.png"
    message.append("行情提示")
    message.append("Bollinger Bands指标")
    call_dingtalk(message, 'news',picurl=pic_path)
    result.to_csv("./Boll.csv", index=False)
